package sclog

import (
    "log"
    "time"
    "runtime"
    "strconv"
    "os"
    "fmt"
)

type Logger struct {

}

const (
    LogFlag = 0
    LogFormat = "[%s] [%s] [%d] [%s] [%s] - %s"
    DateFormat = "2006-01-02 15:04:05.000"
)

func main() {
    test()

}
func test() {
    l := &Logger{}
    f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
    if err != nil {
        l.Error("error")
    }

    defer f.Close()

    log.SetOutput(f)
    log.Println("This is a test log entry")
    l.Info("hello world")
    l.Info("hello world")
    l.Info("hello world")
    l.Info("hello world")
    l.Error("error message")
    l.Exception("dsafdsafgr")
}

func _log(msg interface{}, level string) {
    log.SetFlags(LogFlag)
    os.Mkdir("./go_log", 0777)
    f, err := os.OpenFile("./go_log/sc-" + time.Now().Format("2006-01-02") + ".log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)

    if err != nil {
        log.Print("error to open file")
    }
    defer f.Close()
    log.SetOutput(f)

    pc, file, line, _ := runtime.Caller(2)
    if getShortFileName(file) != "sclog.go"{
        _msg := fmt.Sprintf(LogFormat, time.Now().Format(DateFormat), level, pc, getShortFileName(file) + ":" + strconv.Itoa(line), "", fmt.Sprint(msg))
        log.Printf(_msg)
        fmt.Println(_msg)
    }else {
        pc, file, line, _ := runtime.Caller(3)
        _msg := fmt.Sprintf(LogFormat, time.Now().Format(DateFormat), level, pc, getShortFileName(file) + ":" + strconv.Itoa(line), "", fmt.Sprint(msg))
        log.Printf(_msg)
        fmt.Println(_msg)
    }
}

func (l *Logger) Info(msg interface{}) {
    _log(msg, "INFO")
}

func (l *Logger) Infof(format string, args ...interface{}) {
    l.Info(fmt.Sprintf(format, args...))
}

func (l *Logger) Error(msg interface{}) {
    _log(msg, "ERROR")
}

func (l *Logger) Errorf(format string, args ...interface{}) {
    l.Error(fmt.Sprintf(format, args...))
}

func (l *Logger) Exception(msg interface{}) {
    _log(msg, "EXCEPTION")
}

func (l *Logger) Exceptionf(format string, args ...interface{}) {
    l.Exception(fmt.Sprintf(format, args...))
}

func (l *Logger) Fatal(msg interface{}) {
    _log(msg, "FATAL")
}

func (l *Logger) Fatalf(format string, args ...interface{}) {
    l.Fatal(fmt.Sprintf(format, args...))
}

func (l *Logger) Warning(msg interface{}) {
    _log(msg, "WARNING")
}

func (l *Logger) Warningf(format string, args ...interface{}) {
    l.Warning(fmt.Sprintf(format, args...))
}

func (l *Logger) Debug(msg interface{}) {
    _log(msg, "DEBUG")
}

func (l *Logger) Debugf(format string, args ...interface{}) {
    l.Debug(fmt.Sprintf(format, args...))
}

func getShortFileName(file string) string {
    var short string
    for i := len(file) - 1; i > 0; i-- {
        if file[i] == '/' {
            short = file[i + 1:]
            break
        }
    }
    return short
}

